﻿using UnityEngine;
using System.Collections;
using com.gzc.zgxq.game;
using com.gzc.ThreadLockEvent;

public class AIPlayerModel : BasePlayerModel {

    override public void OnChangeSide ( ) {
        Thinking( );
    }

    override public int MovePiece (int move) {
        return ChessMoveSearchEnginMain.MovePiece(move);
    }
    
    override public void UndoMovePiece (int move, int pcCaptured) {
        ChessMoveSearchEnginMain.UndoMakeMove(move, pcCaptured);
    }

    ChessOnceMoveModel chessOnceMoveModel;
    public void Thinking ( ) {
        // 起新线程搜索
        ChessMoveSearchEnginMain.SearchMain( );
    }

    public AIPlayerModel (ChessGameModel chessGameModel, RedBlackSide mySide)
        : base(chessGameModel, mySide) {

            Init( );
    }

    void Init ( ) {
        InitRedBlackEvaluateValue( );
    }

    void InitRedBlackEvaluateValue ( ) {
        chessBoardModel.TraversePoints((row, col) => {
            this.AddValue(chessBoardModel.Points[row, col].Index256, (int)chessBoardModel.Points[row, col].whichChess);
        });
    }

    

    /// <summary>
    /// 红、黑双方的子力价值
    /// </summary>
    private int valueRed, valueBlack;
    /// <summary>
    /// 局面评价值
    /// </summary>  
    public int Evaluate {
        get {
            return (base.chessGameModel.SidePlayer == RedBlackSide.RED ? valueRed - valueBlack : valueBlack - valueRed) + GameConstant.ADVANCED_VALUE;
        }
    }

    /// <summary>
    /// 在棋盘上放一枚棋子， 局面价值上加
    /// </summary>
    /// <param name="index256">位置下标</param>
    /// <param name="pc">哪颗棋子代号</param>
    public void AddValue (int index256, int pc) {
        // 红方加分，黑方(注意"cucvlPiecePos"取值要颠倒)减分
        // 小于16是红方棋子，大于16为黑方棋子，0表示没棋子
        if (pc < 16) {
            valueRed += GameConstant.cucvlPiecePos[pc - 8][index256];
        } else {
            valueBlack += GameConstant.cucvlPiecePos[pc - 16][ChessMoveSearchEnginUtil.SQUARE_FLIP(index256)];
        }
    }
    /// <summary>
    /// 从棋盘上拿走一枚棋子，当拿走一枚棋子时，要将拿走的该棋子对应该位子的子力价值从该方在该局下的局面价值上减去
    /// </summary>
    /// <param name="sq">256位置下标</param>
    /// <param name="pc">哪颗棋子</param>
    public void DelValue (int sq, int pc) {
        // 红方减分，黑方(注意"cucvlPiecePos"取值要颠倒)加分
        if (pc > 0 && pc < 16) {
            valueRed -= GameConstant.cucvlPiecePos[pc - 8][sq];
        } else {
            valueBlack -= GameConstant.cucvlPiecePos[pc - 16][ChessMoveSearchEnginUtil.SQUARE_FLIP(sq)];
        }
    }

}
